<template>
  <div class="media-library">
    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-row :gutter="16">
        <el-col :span="8">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索文件名或标签"
            clearable
            @change="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="searchForm.category"
            placeholder="选择分类"
            clearable
            @change="handleSearch"
          >
            <el-option label="全部分类" value="" />
            <el-option label="电影" value="电影" />
            <el-option label="音乐" value="音乐" />
            <el-option label="教育" value="教育" />
            <el-option label="新闻" value="新闻" />
            <el-option label="娱乐" value="娱乐" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="searchForm.type"
            placeholder="文件类型"
            clearable
            @change="handleSearch"
          >
            <el-option label="全部类型" value="" />
            <el-option label="视频" value="video" />
            <el-option label="音频" value="audio" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </el-col>
        <el-col :span="4">
          <el-button @click="toggleViewMode">
            <el-icon><Grid v-if="viewMode === 'list'" /><List v-else /></el-icon>
            {{ viewMode === 'list' ? '网格视图' : '列表视图' }}
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 文件列表 - 列表视图 -->
    <el-card v-if="viewMode === 'list'" class="content-card">
      <el-table
        :data="mediaFiles"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="name" label="文件名" min-width="250">
          <template #default="{ row }">
            <div class="file-info">
              <el-image
                v-if="row.type === 'video' && row.thumbnail"
                :src="row.thumbnail"
                class="file-thumbnail"
                fit="cover"
                @click="playMedia(row)"
              />
              <el-icon v-else-if="row.type === 'video'" class="file-icon video">
                <VideoCamera />
              </el-icon>
              <el-icon v-else class="file-icon audio">
                <Headphone />
              </el-icon>
              <div class="file-details">
                <div class="file-name" @click="playMedia(row)">{{ row.name }}</div>
                <div class="file-meta">
                  {{ formatFileSize(row.size) }} · {{ formatDuration(row.duration) }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="type" label="类型" width="80">
          <template #default="{ row }">
            <el-tag :type="row.type === 'video' ? 'primary' : 'success'">
              {{ row.type === 'video' ? '视频' : '音频' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="category" label="分类" width="100" />
        
        <el-table-column prop="views" label="播放量" width="100" />
        
        <el-table-column prop="uploadTime" label="上传时间" width="160" />
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 'ready' ? 'success' : row.status === 'processing' ? 'warning' : 'danger'"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="playMedia(row)">
              <el-icon><VideoPlay /></el-icon>
              播放
            </el-button>
            <el-button size="small" @click="editMedia(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteMedia(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 文件列表 - 网格视图 -->
    <el-card v-else class="content-card">
      <div v-loading="loading" class="grid-container">
        <div
          v-for="file in mediaFiles"
          :key="file.id"
          class="media-card"
          @click="playMedia(file)"
        >
          <div class="media-preview">
            <el-image
              v-if="file.type === 'video' && file.thumbnail"
              :src="file.thumbnail"
              class="preview-image"
              fit="cover"
            />
            <div v-else class="preview-placeholder">
              <el-icon size="48">
                <VideoCamera v-if="file.type === 'video'" />
                <Headphone v-else />
              </el-icon>
            </div>
            <div class="play-overlay">
              <el-icon size="32"><VideoPlay /></el-icon>
            </div>
            <div class="duration-badge">{{ formatDuration(file.duration) }}</div>
          </div>
          
          <div class="media-info">
            <div class="media-title">{{ file.name }}</div>
            <div class="media-meta">
              <span>{{ formatFileSize(file.size) }}</span>
              <span>{{ file.views }} 次播放</span>
            </div>
            <div class="media-tags">
              <el-tag
                v-for="tag in file.tags.slice(0, 2)"
                :key="tag"
                size="small"
                style="margin-right: 4px;"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
          
          <div class="media-actions">
            <el-button size="small" @click.stop="editMedia(file)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button size="small" type="danger" @click.stop="deleteMedia(file)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[12, 24, 48, 96]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑对话框 -->
    <MediaEditDialog
      v-model="showEditDialog"
      :media="currentMedia"
      @updated="handleMediaUpdated"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { mediaApi } from '@/api/modules/media'
import type { MediaFile, PaginationParams } from '@/types'
import MediaEditDialog from '@/components/MediaEditDialog.vue'

const router = useRouter()

const loading = ref(false)
const viewMode = ref<'list' | 'grid'>('list')
const mediaFiles = ref<MediaFile[]>([])
const selectedFiles = ref<MediaFile[]>([])
const showEditDialog = ref(false)
const currentMedia = ref<MediaFile>()

// 搜索表单
const searchForm = reactive({
  keyword: '',
  category: '',
  type: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 12,
  total: 0
})

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化时长
const formatDuration = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes}:${secs.toString().padStart(2, '0')}`
}

// 获取状态文本
const getStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    ready: '就绪',
    processing: '处理中',
    error: '错误'
  }
  return statusMap[status] || status
}

// 切换视图模式
const toggleViewMode = () => {
  viewMode.value = viewMode.value === 'list' ? 'grid' : 'list'
}

// 加载媒体文件
const loadMediaFiles = async () => {
  loading.value = true
  try {
    const params: PaginationParams = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword || undefined,
      category: searchForm.category || undefined,
      type: searchForm.type as any || undefined
    }
    
    const result = await mediaApi.getMediaFiles(params)
    mediaFiles.value = result.list
    pagination.total = result.total
  } catch (error) {
    ElMessage.error('加载文件列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadMediaFiles()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadMediaFiles()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadMediaFiles()
}

// 选择改变
const handleSelectionChange = (selection: MediaFile[]) => {
  selectedFiles.value = selection
}

// 播放媒体
const playMedia = (media: MediaFile) => {
  router.push(`/player/${media.id}`)
}

// 编辑媒体
const editMedia = (media: MediaFile) => {
  currentMedia.value = media
  showEditDialog.value = true
}

// 删除媒体
const deleteMedia = async (media: MediaFile) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文件 "${media.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await mediaApi.deleteMediaFile(media.id)
    ElMessage.success('删除成功')
    loadMediaFiles()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 媒体更新
const handleMediaUpdated = () => {
  loadMediaFiles()
}

onMounted(() => {
  loadMediaFiles()
})
</script>

<style scoped>
.media-library {
  padding: 0;
}

.search-card {
  margin-bottom: 16px;
}

.content-card {
  margin-bottom: 16px;
}

.file-info {
  display: flex;
  align-items: center;
}

.file-thumbnail {
  width: 60px;
  height: 40px;
  border-radius: 4px;
  margin-right: 12px;
  cursor: pointer;
}

.file-icon {
  width: 60px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  margin-right: 12px;
  font-size: 20px;
}

.file-icon.video {
  background: #e6f7ff;
  color: #1890ff;
}

.file-icon.audio {
  background: #f6ffed;
  color: #52c41a;
}

.file-details {
  flex: 1;
}

.file-name {
  font-weight: 500;
  cursor: pointer;
  color: #1890ff;
  margin-bottom: 4px;
}

.file-name:hover {
  text-decoration: underline;
}

.file-meta {
  font-size: 12px;
  color: #666;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  min-height: 200px;
}

.media-card {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.media-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.media-preview {
  position: relative;
  height: 160px;
  background: #f5f5f5;
}

.preview-image {
  width: 100%;
  height: 100%;
}

.preview-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ccc;
}

.play-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 48px;
  height: 48px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.media-card:hover .play-overlay {
  opacity: 1;
}

.duration-badge {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.media-info {
  padding: 12px;
}

.media-title {
  font-weight: 500;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.media-meta {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.media-meta span {
  margin-right: 12px;
}

.media-tags {
  margin-bottom: 8px;
}

.media-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.media-card:hover .media-actions {
  opacity: 1;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
</style> 